import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import morgan from 'morgan';
import rateLimit from 'express-rate-limit';
import swaggerUi from 'swagger-ui-express';

import { connectDatabase } from '@/config/database';
import { specs } from '@/config/swagger';
import { config, validateConfig } from '@/config/env';

// 导入路由
import authRoutes from '@/routes/auth';
import vehicleRoutes from '@/routes/vehicles';
import expenseRoutes from '@/routes/expenses';
import incomeRoutes from '@/routes/incomes';
import statisticsRoutes from '@/routes/statistics';
import chartsRoutes from '@/routes/charts';
import exportRoutes from '@/routes/export';
import configRoutes from '@/routes/config';
import oilPriceRoutes from '@/routes/oilPrices';
import locationRoutes from '@/routes/location';

const app = express();

// 验证配置
validateConfig();

// 中间件
app.use(helmet());
app.use(compression());

// CORS配置
const corsOptions = {
  origin: function (origin: string | undefined, callback: Function) {
    // 允许的源列表
    const allowedOrigins = config.corsOrigin
      .split(',')
      .map(origin => origin.trim());

    // 允许没有origin的请求（比如同源请求）
    if (!origin) {
      return callback(null, true);
    }

    // 检查origin是否在允许列表中
    if (allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      console.warn(`⚠️  CORS blocked request from origin: ${origin}`);
      callback(new Error('Not allowed by CORS'));
    }
  },
  credentials: true,
  optionsSuccessStatus: 200, // 某些浏览器需要这个
};

app.use(cors(corsOptions));

// 请求日志
app.use(morgan('combined'));

// 速率限制
const limiter = rateLimit({
  windowMs: config.rateLimitWindowMs,
  max: config.rateLimitMaxRequests,
  message: {
    success: false,
    message: '请求过于频繁，请稍后再试',
  },
});
app.use('/api/', limiter);

// 解析JSON
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// API文档
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));

// 健康检查
app.get('/health', (_req, res) => {
  res.status(200).json({
    success: true,
    message: 'AutoCost API 服务运行正常',
    timestamp: new Date().toISOString(),
    version: '1.0.0',
  });
});

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/cars', vehicleRoutes);
app.use('/api/expenses', expenseRoutes);
app.use('/api/incomes', incomeRoutes);
app.use('/api/statistics', statisticsRoutes);
app.use('/api/charts', chartsRoutes);
app.use('/api/export', exportRoutes);
app.use('/api/config', configRoutes);
app.use('/api/oil-prices', oilPriceRoutes);
app.use('/api/location', locationRoutes);

// 404处理
app.use('*', (_req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在',
  });
});

// 错误处理中间件
app.use(
  (
    err: any,
    _req: express.Request,
    res: express.Response,
    _next: express.NextFunction
  ) => {
    console.error('Error:', err);

    res.status(err.status || 500).json({
      success: false,
      message: err.message || '服务器内部错误',
    });
  }
);

// 启动服务器
const startServer = async () => {
  try {
    // 连接数据库
    await connectDatabase();

    // 启动服务器
    const port = config.port;
    app.listen(port, () => {
      console.log(`🚀 AutoCost API 服务器启动成功`);
      console.log(`📍 服务器地址: http://localhost:${port}`);
      console.log(`📚 API文档: http://localhost:${port}/api-docs`);
      console.log(`🔍 健康检查: http://localhost:${port}/health`);
    });
  } catch (error) {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  }
};

// 启动服务器
startServer();

export { app };
